<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 -->
<!-- 
* @desc:角色管理编辑权限弹出框组件
* @fileName:role-permission.vue
* @author:zhouyongjie@yzbdl.ac.cn
* @date:2022-4-6
!-->

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import { FormInstance } from "element-plus";
import treeMenu from "@/common/enum/tree-menu";
import { showErrorMessage, showSuccessMessage } from "@/common/message";
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;
//接收父组件传值
const props = defineProps({
  handlePreFunc: Function as any,
  PreFunc: Function as any,
  PreItem: Object as any,
});
//定义参数
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const checkShow = ref(false);
let treeMenuC = JSON.parse(JSON.stringify(treeMenu));
let newtreeMenuC = JSON.parse(JSON.stringify(treeMenu));
//判断显隐
const permissionShow = ref(false);
//选择框参数
const checkBox = reactive({
  list: [] as any,
});
//所有权限
const permissionList = reactive({
  list: [] as any,
});
//选中的权限
const chooseBox = reactive({
  list: [] as any,
});
let permissionIds = reactive({
  ids: [] as any,
});

//表单方向
const labelPosition = ref("left");
//树形菜单默认
const defaultProps = {
  children: "children",
  label: "text",
  class: "isexiststyle",
};
let ruleForm = reactive({
  list: props.PreItem,
  treedata: treeMenuC,
  newTreeData: newtreeMenuC,
});
// 默认选中节点集合
const defaultChecked = reactive({
  list: [] as any,
});
/**
 * @description:获取权限菜单
 * @return void
 */
const getPermission = () => {
  defaultChecked.list = [];
  const res = proxy.$HTTP.get({
    url: `/permission`,
  });
  res.then((res: any) => {
    if (res.isOk) {
      permissionList.list = res.data;
      // 拼装权限树
      res.data.forEach((ids: any) => {
        ids["text"] = ids.permissionName;
        ruleForm.treedata.forEach((tree: any) => {
          if (tree.children.length > -1) {
            tree.children.forEach((tree1: any) => {
              if (tree1.key !== "" && tree1.key !== null) {
                if (ids.menuUrl === tree1.key) {
                  tree1.children.push(ids);
                }
              } else {
                tree1.children.forEach((tree2: any) => {
                  if (ids.menuUrl === tree2.key) {
                    tree2.children.push(ids);
                  }
                });
              }
            });
          }
        });
      });
      ruleForm.list.permissions.forEach((item: any) => {
        res.data.forEach((ids: any) => {
          if (item.id === ids.id) {
            defaultChecked.list.push(ids.id);
          }
        });
      });
      nextTick(() => {
        proxy.$refs.ruleTree.setCheckedKeys(defaultChecked.list, true);
      });
    }
  });
};

const ruleTree: any = ref();

/**
 * @description:提交表单
 * @param {FormInstance | undefined} formEl
 * @return void
 */
const submitForm = (formEl: FormInstance | undefined) => {
  const res = proxy.$HTTP.post({
    url: `/role/${ruleForm.list.id}/permission`,
    data: Array.from(new Set(clearData(ruleTree.value!.getCheckedKeys(false)))),
  });
  res.then((res: any) => {
    if (res.isOk) {
      props.handlePreFunc(res.isOk);
      defaultChecked.list = [];
      showSuccessMessage({ message: "修改成功！" });
    }
  });
  res.catch((error: any) => {
    if (error.data instanceof Array) {
      showErrorMessage({
        message: error.data[0].errorMsg,
      });
    } else {
      showErrorMessage({
        message: error.data,
      });
    }
  });
};

/**
 * @description:清洗数据
 * @param {any} arr
 * @return {any} 清洗后的数组
 */
const clearData = (arr: any) => {
  return arr.filter((item: string | string[]) => item.indexOf("-") < 0);
};

//初始化数据
onMounted(() => {
  //获取权限
  getPermission();
  if (ruleForm.list.permissions.length > 0) {
    ruleForm.list.permissions.map((item: any) => {
      chooseBox.list.push(item.id);
    });
  }
});
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :label-position="labelPosition"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
  >
    <el-form-item label="权限修改">
      <!-- 新的权限树 -->
      <el-tree
        ref="ruleTree"
        :data="ruleForm.treedata"
        :default-expand-all="true"
        :default-checked-keys="defaultChecked.list"
        show-checkbox
        node-key="id"
        :props="defaultProps"
      >
      </el-tree>
    </el-form-item>
    <el-form-item class="ClickButton">
      <el-button @click="submitForm(ruleFormRef)">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-family: PingFang SC;
  font-weight: 700;
  color: #000000;
  font-size: 14px;
}

:deep(.el-tree-node__content) {
  height: 32px !important;
}
:deep(.el-input) {
  height: 40px;
  background-color: #ffffff;
}
:deep(.el-textarea) {
  height: 100px;
  background-color: #ffffff;
  .el-textarea__inner {
    height: 100px;
  }
}

.treeContent {
  width: 340px;
  float: left;
  .title {
    width: 340px;
    color: rgba(0, 0, 0, 0.5);
    background-color: #f5f5f5;
    font-size: 14px;
    font-weight: 700;
    text-align: center;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .imgSelect {
      margin-right: 120px;
    }
  }
  .active {
    background-color: rgba(245, 245, 245, 1);
    width: 300px;
  }
}
.boxContent {
  width: 340px;
  height: 370px;
  padding-left: 20px;
  float: left;
  .title {
    width: 340px;
    color: rgba(0, 0, 0, 0.5);
    background-color: #f5f5f5;
    font-size: 14px;
    font-weight: 700;
    text-align: center;
  }
}
.ClickButton {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end;

    .el-button {
      height: 40px;
      background-color: #ffffff;
      border: 1px solid;
      border-color: #cccccc;
    }
  }
}
</style>
